package hou;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test10 {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        Class c1 = Class.forName("hou.User");

        User use = (User) c1.newInstance();
        System.out.println(use);

        Constructor constructor = c1.getConstructor(String.class, int.class);
        User user2 = (User) constructor.newInstance("hou", 18);
        System.out.println(user2);

        //通过反射调用方法
        User user3 = (User) c1.newInstance();
        Method setname = c1.getMethod("setName", String.class);
        setname.invoke(user3, "dong");
        System.out.println(user3.getName());

        //获取反射操作属性
        User user4 = (User) c1.newInstance();
        Field field = c1.getDeclaredField("age");
        field.setAccessible(true);
        field.set(user4, 100);
        System.out.println(user4.getAge());
    }
}
